"use client";
import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { useRouter } from 'next/navigation';
import { updateUser } from '@/util/actions/userAction';

const { Item: FormItem } = Form;

const EditUserClient = ({ user, token }) => {
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const router = useRouter();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      if (!token) throw new Error("No token found");

      const response = await updateUser(values, token);  // Store the response
      console.log("更新响应:", response);  // Add debug log
      message.success("用户信息更新成功");
      router.push("/userManage");
    } catch (error) {
      console.error("更新用户信息时出错:", error);  // Log the error for debugging
      message.error(error.message || "更新用户信息失败");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 400, margin: "auto", padding: "20px" }}>
      <h1>修改用户信息</h1>
      <Form
        form={form}
        name="editUser"
        onFinish={onFinish}
        initialValues={user}
        autoComplete="off"
      >
        <FormItem
          label="用户名"
          name="username"
          rules={[{ required: true, message: "请输入用户名!" }]}
        >
          <Input />
        </FormItem>
        <FormItem
          label="邮箱"
          name="email"
          rules={[
            { required: true, message: "请输入邮箱!" },
            { type: "email", message: "请输入有效的邮箱地址!" },
          ]}
        >
          <Input />
        </FormItem>
        <FormItem
          label="密码"
          name="password"
          rules={[{ required: true, message: "请输入密码!" }]}
        >
          <Input.Password />
        </FormItem>
        <FormItem>
          <Button type="primary" htmlType="submit" loading={loading} block>
            更新
          </Button>
        </FormItem>
      </Form>
    </div>
  );
};

export default EditUserClient;
